import type { AxiosRequestConfig, AxiosInstance } from 'axios';
import Instance from './instance';

type RequestMethod = 'get'| 'post' | 'put' | 'delete'

interface RequestParam {
  url: string;
  method: RequestMethod;
  data?: any;
  query?: any;
  config?: AxiosRequestConfig;
}

export function createRequest(axiosConfig: AxiosRequestConfig){
  const { instance } = new Instance(axiosConfig);

  async function asyncRequest<T>(params: RequestParam):Promise<Service.SuccessResult<T>>{
    const { url, method, config } = params;
    return  await getRequestResponse({
      instance, url, method, config, data: params?.data
    });
  }

  function get<T>(url: string, config?: AxiosRequestConfig){
    return asyncRequest<T>({ url, method: 'get', config});
  };

  function post<T, U>(url:string, data:U, config?:AxiosRequestConfig){
    return asyncRequest<T>({ url, method: 'post', data, config});
  }
  return {
    get,
    post
  };
}

async function getRequestResponse(params: {
  instance: AxiosInstance;
  method: RequestMethod;
  url: string;
  data?: any;
  config?: AxiosRequestConfig;
}) {
  const { instance, method, url, data, config } = params;

  let res: any;
  if (method === 'get' || method === 'delete') {
    res = await instance[method](url, config);
  } else {
    res = await instance[method](url, data, config);
  }
  return res.data ? res?.data : res;
}
